# ！ /usr/bin/python3
# -*- coding:utf-8 -*-
# @Author:Peng Cao
# @File: 11img_信用卡识别.py
# @Software: PyCharm

import cv2.cv2 as cv
import matplotlib.pyplot as plt
import numpy as np
import argparse


# # 设置参数
# ap = argparse.ArgumentParser()
# ap.add_argument("-i", "--image", required=True, help="path to input image")
# ap.add_argument('-t', "--template", required=True, help='path to template OCR-A image')
# args = vars(ap.parse_args())
# # 图层信用卡类型
# FIRST_NUMBER = {
#     "3": "American EXpress",
#     "4": "Visa",
#     "5": "MasterCard",
#     "6": "Discover Card"
# }


def cv_show(name, img):
    """
    展示图片
    :param name:
    :param img:
    :return:
    """

    cv.imshow(winname=name, mat=img)
    cv.waitKey(0)
    cv.destroyAllWindows()


def cts_sort(cts, method='left-to-right'):
    reverse = False
    i = 0
    if method == "right-to-left" or method == 'bottom-to-top':
        reverse = True
    if method == 'top-to-bottom' or method == 'bottom-to-top':
        i = 1
    boundingBoxes = [cv.boundingRect(ct) for ct in cts]
    (cts, boundingBoxes) = zip(*sorted(zip(cts, boundingBoxes), key=lambda b: b[1][i], reverse=reverse))
    return cts, boundingBoxes


def img_resize(img, width):
    """
    根据图片宽度，同比例，重置图片大小
    :param img:
    :param width:
    :return:
    """
    if isinstance(img, str):
        img = cv.imread(filename=img)
    else:
        img = img
    org_size = img.shape
    val = width / org_size[1]
    new_img = cv.resize(img, (0, 0), fx=val, fy=val)
    return new_img


def img_contours():
    """
    给图像画轮廓
    :return:
    """
    img = cv.imread('./data/imgs_credit/ocr_a_reference.png')
    img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)  # 将原始图片转换为灰度模式
    thresh, new_img = cv.threshold(src=img_gray, thresh=127, maxval=255, type=cv.THRESH_BINARY_INV)  # 阈值操作
    cts, new_img2 = cv.findContours(image=new_img.copy(), mode=cv.RETR_EXTERNAL, method=cv.CHAIN_APPROX_SIMPLE)  # 获取轮廓值
    # 轮廓排序
    cts, boundingBoxes = cts_sort(cts, method='left-to-right')
    digits = {}
    for (i, c) in enumerate(cts):
        (x, y, w, h) = cv.boundingRect(c)
        roi = new_img[y:y + h, x:x + w]
        roi = cv.resize(roi, (57, 88))
        digits[i] = roi
    # 初始化卷积核
    rectKernel = cv.getStructuringElement(cv.MORPH_RECT, (9, 3))
    sqKernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))
    # ------------------------------------------------------#
    image = cv.imread("./data/imgs_credit/credit_card_01.png")
    cv_show("image", image)
    image = img_resize(image, width=300)
    img_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    cv_show("image2", img_gray)
    # 礼帽操作，突出更明亮的区域
    tophat = cv.morphologyEx(img_gray, cv.MORPH_TOPHAT, rectKernel)
    cv_show('tophat', tophat)
    #
    gradX = cv.Sobel(tophat, ddepth=cv.CV_32F, dx=1, dy=0, ksize=-1)
    gradX = np.absolute(gradX)
    (minVal, maxVal) = (np.min(gradX), np.max(gradX))
    gradX = (255 * ((gradX - minVal) / (maxVal - minVal)))
    gradX = gradX.astype('uint8')
    cv_show('gradX', gradX)
    # 通过团操作（先膨胀，再腐蚀），将数字连在一起
    gradX = cv.morphologyEx(gradX, cv.MORPH_CLOSE, rectKernel)
    cv_show('gradX', gradX)
    new_img = cv.threshold(gradX, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)[1]
    cv_show('new_img', new_img)
    # 再来一个团操作

    exit()
    for i in range(len(cts)):
        img_with_contours = cv.drawContours(image=img.copy(), contours=[cts[i]], contourIdx=-1, color=(255, 0, 255), thickness=2)
        cv_show(f'img{i}', img_with_contours)
    img_with_contours = cv.drawContours(image=img.copy(), contours=[cts[0]], contourIdx=-1, color=(0, 0, 255), thickness=2)
    cv_show("img_with_contours", img_with_contours)
    return cts, img_with_contours


if __name__ == '__main__':
    img_contours()
